<template>
  <div class="vc-page msg-notice-maintain-page">
    <div>
      <!-- 顶部按钮 -->
      <el-row class="vc-btns">
        <el-button v-for="btn in optBtns" :key="btn.label" :type="btn.type" size="small" @click="btn.fn()">{{ btn.label }}</el-button>
      </el-row>

      <!-- 表单 -->
      <el-form ref="noticeForm" :model="noticeForm" :rules="rules" label-width="90px" size="small">
        <el-form-item label="重要程度" prop="urgency">
          <el-select
            v-model="noticeForm.urgency"
            style="width: 180px"
            suffix-icon="el-icon-arrow-down"
            readonly>
            <el-option
              v-for="item in urgencyList"
              :key="item.code"
              :value="item.code"
              :label="item.name">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="标题" prop="title">
          <el-input v-model="noticeForm.title" maxlength="50" placeholder="请输入" clearable @clear="$refs.noticeForm.validateField('title')"></el-input>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input v-model="noticeForm.content" maxlength="1000" placeholder="请输入"
                    type="textarea" class="scrollbar" show-word-limit></el-input>
        </el-form-item>

        <el-form-item label="发送范围" prop="users" class="form-item-users">
          <ul class="selected-tags" v-if="noticeForm.users.length">
            <template v-for="(user, idx) in noticeForm.users">
              <li v-if="idx < 8" :key="user.id">
                <span class="text-ellipsis">{{ user.nickname }}</span>
                <i class="el-icon-close" @click="removeUser(idx)"></i>
              </li>
            </template>
            <span v-if="noticeForm.users.length > 8">...</span>
            <el-button type="text" size="small" class="btn-text-only" @click="openSelectUser()">修改</el-button>
          </ul>

          <el-button v-else type="text" size="small" class="btn-text-only" @click="openSelectUser()"><i class="el-icon-plus"></i>添加</el-button>
          <div class="el-form-item__error" v-show="usersValid && !noticeForm.users.length">请选择发送范围</div>
        </el-form-item>

        <el-form-item label="附件上传" prop="attmts">
          <upload-file ref="filesData" :fileData="noticeForm.attmts" class="cls-upload-file"/>
        </el-form-item>
      </el-form>

      <!-- 修改发送范围 - 选择用户 -->
      <select-box
        :allNode="selectUser.allNode"
        :boxDialogVisible="selectUser.editVisible"
        :checkedNode="selectUser.checked"
        :iconConfig="selectUser.iconConfig"
        :rightKeyQ="selectUser.rightKeyQ"
        :searchConfig="selectUser.search"
        :title="selectUser.title"
        @close="selectUser.editVisible = false"
        @callback="getSelectUsers"/>

      <!-- 设置发布时间 -->
      <scheduled-release :dialogVisible="timingDialogVisible" @close="closeTimingDialog"/>
    </div>
  </div>
</template>

<script>
import qs from 'qs'
import SelectBox from '_c/selectBox'
import ScheduledRelease from './scheduledRelease'
import UploadFile from './uploadFile'
import { validateInput } from '@/utils/validator'

export default {
  name: 'noticeMaintain',
  components: { SelectBox, ScheduledRelease, UploadFile },
  data () {
    return {
      isAddOrEdit: this.$route.params.id === 'add',
      noticeForm: {
        urgency: '1',
        title: '',
        content: '',
        users: [],
        attmts: []
      },
      rules: {
        urgency: [
          { required: true, message: '请选择重要程度', trigger: ['blur', 'change'] }
        ],
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { validator: validateInput, trigger: 'blur' }
        ]
      },
      selectUser: {
        editVisible: false,
        title: '选择用户',
        rightKeyQ: 'nickname',
        iconConfig: {
          parentType: {
            key: 'org',
            icon: 'vc-icon vc-icon-tree-org'
          },
          childrenType: {
            key: 'user',
            icon: 'vc-icon vc-icon-tree-user'
          }
        },
        search: {
          title: '请输入',
          patch: 'getUserByUsername',
          key: 'nickname',
          params: {}
        },
        allNode: [],
        checked: []
      },
      usersValid: false,
      timingDialogVisible: false,
      disabled: false,
      defaultBtns: [
        { label: '保存',
          fn: () => {
            this.handleForm('saveNotice', '保存')
          }
        },
        { label: '定时发布',
          fn: this.scheduledRelease
        },
        { label: '发布',
          type: 'primary',
          fn: () => {
            this.handleForm('releaseNotice', '发布')
          }
        }
      ],
      optBtns: []
    }
  },
  computed: {
    urgencyList () {
      return this.$store.state.dic.listFormat['xxtzzycd']
    }
  },
  watch: {
    'noticeForm.users': {
      handler (val) {
        val && val.length && (this.usersValid = false)
      }
    }
  },
  created () {
    this.isAddOrEdit ? (this.optBtns = this.defaultBtns) : this.getFormData()
  },
  methods: {
    /**
     * 获取表单数据
     */
    getFormData () {
      this.$api.findNoticeInfoById({
        data: qs.stringify({
          id: this.$route.params.id
        })
      }).then(res => {
        if (!res.success || !res.data) {
          return
        }
        this.noticeForm = res.data
        this.optBtns = [{ label: '删除', fn: this.isRemove }, ...this.defaultBtns]
      })
    },
    /**
     * 打开选择用户弹出框
     */
    openSelectUser () {
      this.selectUser.checked = this.noticeForm.users.map(item => {
        return { id: item.userId, nickname: item.nickname }
      })
      this.$api.getTreeData().then(res => {
        if (!res.success) {
          return
        }
        res.data[0] = res.data[0] || []
        res.data[1] = res.data[1] || []
        res.data[1].forEach(i => {
          if (!i.pid && i.type === 'user') {
            i.pid = 'other'
          }
        })
        this.selectUser.allNode = res.data[0].concat(res.data[1])
        this.selectUser.allNode.push({
          id: 'other',
          text: '其他',
          children: [],
          type: 'org',
          pid: null
        })
        this.selectUser.editVisible = true
      })
    },
    /**
     * 获取选择用户
     */
    getSelectUsers (data) {
      this.noticeForm.users = data.map(item => {
        return { userId: item.id, nickname: item.nickname }
      })
      this.selectUser.editVisible = false
    },
    /**
     * 移除选中的用户
     */
    removeUser (idx) {
      this.noticeForm.users.splice(idx, 1)
    },
    /**
     * 表单处理
     */
    handleForm (api, opera) {
      let attmts = []
      files = this.$refs.filesData.filesTableData || []
      for (let item of files) {
        if (item.fileName && (!item.fileId || item.percent < 100)) {
          return this.$notifyBox('存在未上传完成的附件，请等待上传完成', 'warning')
        }
        attmts.push({ attmtId: item.fileId, attmtName: item.fileName, attmtSize: item.fileSize })
      }
      this.noticeForm.attmts = attmts
      this.usersValid = opera.includes('发布')
      this.$refs.noticeForm.validate(valid => {
        if (!valid || (this.usersValid && !this.noticeForm.users.length)) {
          return false
        }
        if (typeof api === 'function') {
          return api()
        }
        this.handleEvent(api, opera, this.usersValid)
      })
    },
    /**
     * 事件处理
     */
    handleEvent (api, opera, back) {
      if (this.disabled) {
        return
      }
      this.disabled = true
      this.$api[api]({
        data: this.noticeForm
      }).then(res => {
        if (!res.success) {
          this.disabled = false
          return
        }
        this.timingDialogVisible = false
        this.$notifyBox(`${opera}成功`, 'success')
        if (back) {
          return this.GLOBAL.app.closeCurrTab(this.$route.path)
        }
        if (!this.isAddOrEdit) {
          this.disabled = false
          this.noticeForm = res.data
          return
        }
        const _this = this
        this.$store.commit('DEL_TAB', _this.$route.path)
        this.$router.push({
          name: 'noticeMaintain',
          params: {
            id: res.data && res.data.id,
            meta: {
              title: '修改通知'
            }
          }
        })
      }).catch(() => {
        this.disabled = false
      })
    },
    /**
     * 定时发布
     */
    scheduledRelease () {
      this.handleForm(() => {
        this.timingDialogVisible = true
      }, '定时发布')
    },
    /**
     * 关闭定时发布弹出框
     */
    closeTimingDialog (val) {
      if (!val) {
        this.timingDialogVisible = false
        return
      }
      this.noticeForm.releaseTime = val
      this.handleEvent('releaseNoticeByTime', '定时发布', true)
    },
    /**
     * 确认删除
     */
    isRemove () {
      this.$confirmBox(this.handleRemove)
    },
    /**
     * 删除
     */
    handleRemove () {
      this.$api.removeNoticeById({
        data: qs.stringify({
          id: this.noticeForm.id
        })
      }).then(res => {
        res.success && this.$notifyBox('删除成功', 'success')
        this.GLOBAL.closeCurrTab()
      })
    }
  }
}
</script>

<style lang="less">
.msg-notice-maintain-page {
  height: calc(100% - 30px);
  & > div {
    width: calc(100% - 30px);
    margin-bottom: 15px;
    padding: 15px;
    background: #fff;
    .vc-btns {
      justify-content: flex-end;
    }
    .el-form {
      .el-form-item:last-child {
        margin-bottom: 0;
      }
      .el-form-item > .el-form-item__content {
        text-align: left;
      }
      .el-textarea {
        .el-textarea__inner {
          height: 25vh;
          padding: 5px 15px 20px;
          resize: none;
        }
        .el-input__count {
          width: calc(100% - 16px);
          text-align: right;
        }
      }
      .selected-tags {
        height: 32px;
        margin: 0;
        padding: 0;
        display: flex;
        align-items: center;
        & > span, & > button {
          margin-left: 5px;
        }
        li {
          & + li {
            margin-left: 10px;
          }
          position: relative;
          display: inline-block;
          height: 22px;
          line-height: 22px;
          padding-left: 5px;
          border: 1px solid rgba(226,226,226,1);
          border-radius: 2px;
          span {
            display: inline-block;
            max-width: 70px;
          }
          .el-icon-close {
            position: relative;
            bottom: 6px;
            right: 6px;
            margin-left: 6px;
            font-size: 10px;
            font-weight: bold;
            color: #B7B7B7;
            cursor: pointer;
            &:hover {
              font-weight: bold;
              color: red;
            }
          }
        }
      }
      .form-item-users {
        .el-form-item__label::before {
          content: '*';
          color: #FF7575;
          margin-right: 4px;
        }
        .el-form-item__error {
          padding-top: 0px;
          margin-top: -4px;
        }
      }
      .cls-upload-file {
        margin-top: -4px;
      }
    }
  }
}
</style>
